package com.youbug.kefu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.youbug.kefu.entity.Menu;
import com.youbug.kefu.entity.Org;
import com.youbug.kefu.entity.User;
import com.youbug.kefu.mapper.OrgMapper;
import com.youbug.kefu.service.IOrgService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youbug.kefu.service.IUserService;
import net.bytebuddy.asm.Advice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * <p>
 * 机构表 服务实现类
 * </p>
 *
 * @author youbug
 * @since 2023-03-02
 */
@Service
@Transactional
public class OrgServiceImpl extends ServiceImpl<OrgMapper, Org> implements IOrgService {
    @Autowired
    private IUserService userService;

    @Override
    public List<Org> getOrgs() {

        List<Org> orgList = this.list();

        return getSubOrgs(orgList,0);
    }

    @Override
    public List<Org> getParentOrgs() {
        QueryWrapper<Org> wrapper = new QueryWrapper<>();

        wrapper.in("level",1,2);

        List<Org> list = this.list(wrapper);

        return getSubOrgs(list,0);
    }

    @Override
    public boolean deleteOrgById(String id) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();

         userQueryWrapper.eq("org_id", id);

        int count = userService.count(userQueryWrapper);

        if(count == 0){
            boolean remove = this.removeById(id);
            return true;
        }
        return false;
    }

    @Override
    public boolean updateOrgById(Org org) {

        boolean update = this.updateById(org);

        if(update){
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();

            userQueryWrapper.eq("org_id", org.getId());

            User user = new User();
            user.setOrgId(org.getId());
            user.setOrgName(org.getName());

            userService.update(user, userQueryWrapper);
        }

        return update;
    }

    private List<Org> getSubOrgs(List<Org> orgList, Integer pid) {

        List<Org> subOrgs = new ArrayList<>();

        Iterator<Org> iterator = orgList.iterator();

        while(iterator.hasNext()){

            Org temp = iterator.next();

            if(temp.getPid().equals(pid)){

                List<Org> menuTemps = getSubOrgs(orgList, temp.getId());

                temp.setChildren(menuTemps);

                subOrgs.add(temp);
            }
        }

        return subOrgs;
    }
}
